import logging
from types import SimpleNamespace

from app.config.config import settings
from app.models.theme_model import ThemeModel
import os
import csv

from app.utils.file_decode_util import check_file_encoding


class ThemeService:
    def query_theme(self, themeModel: ThemeModel):
        theme_path: str = settings.theme_path
        all_items = os.listdir(theme_path)
        files = dict()
        file_name: str = self.ensure_csv_suffix(themeModel.theme_name)
        for item in all_items:
            full_path = os.path.join(theme_path, item)
            if os.path.isfile(full_path):
                files[item] = full_path
        flag: bool = False
        if files[file_name] is not None:
            # 读取文件
            flag = True

        if not flag:
            return "主题文件不存在"
        file_encodings = check_file_encoding(files[file_name])
        with open(files[file_name], mode='r', encoding=file_encodings) as file:
            csv_reader = csv.reader(file, delimiter=',')  # 用逗号分隔
            # next(csv_reader)  # 跳过第一行（表头）
            data_dict = {row[0]: row[1] for row in csv_reader if len(row) >= 2}  # 提取第一列和第二列并作为字典返回
        if themeModel.vehicle_no in data_dict:
            return f"设备号:{themeModel.vehicle_no}存在主题信息：{data_dict[themeModel.vehicle_no]}"  # 返回对应的第二列数据
        else:
            return f"设备号:{themeModel.vehicle_no}不存在主题信息"

    def query_theme_withjson(self, body: dict):
        themeModel: ThemeModel = SimpleNamespace(**body)
        return self.query_theme(themeModel)

    def ensure_csv_suffix(self, filename):
        # 分割文件名和后缀
        root, ext = os.path.splitext(filename)
        # 如果后缀不是 .csv（忽略大小写），则拼接 .csv
        if ext.lower() != '.csv':
            filename = root + '.csv'
        return filename


theme_service = ThemeService()
